<template>
  <div class="login">
    <div class="login_main">
      <div class="header">
        <div class="header_main">
          <!-- <div class="header_left">淘宝高佣选品库</div> -->
          <logo></logo>
          <div class="header_action">
            <a href="#" class="action_box">
              <img :src="require('@/assets/images/man.png')" alt="" />
              <p>人工审核</p>
            </a>
            <a href="#" class="action_box">
              <img :src="require('@/assets/images/search.png')" alt="" />
              <p>实时排查</p>
            </a>
            <a href="#" class="action_box">
              <img :src="require('@/assets/images/tags.png')" alt="" />
              <p>持续更新</p>
            </a>
          </div>
        </div>
      </div>
      <div class="login_content">
        <div class="content_main">
          <div class="login_box">
            <el-card class="box-card">
              <div class="login_tabs">
                <el-tabs v-model="activeName" @tab-click="handleClick">
                  <el-tab-pane label="登录" name="login">
                    <div>
                      <el-form
                        :model="loginForm"
                        status-icon
                        :rules="rules"
                        ref="ruleForm"
                        label-width="100px"
                        class="demo-ruleForm"
                      >
                        <el-form-item prop="phone">
                          <el-input
                            placeholder="请输入手机号码"
                            v-model.number="loginForm.phone"
                            clearable
                            class="phonenumipt"
                          >
                            <i
                              slot="prefix"
                              style="font-size:20px;color:#666666;font-weight: bold;"
                              class="el-input__icon el-icon-mobile-phone"
                            ></i>
                          </el-input>
                        </el-form-item>

                        <el-form-item prop="pass">
                          <el-input
                            type="password"
                            placeholder="请输入密码"
                            v-model.trim="loginForm.pass"
                            autocomplete="off"
                            show-password
                            class="phonenumipt"
                          >
                            <i
                              slot="prefix"
                              style="font-size:20px;color:#666666;font-weight: bold;"
                              class="el-input__icon el-icon-lock"
                            ></i>
                          </el-input>
                        </el-form-item>
                        <!-- 阿里人机验证 -->
                        <!-- <el-form-item prop="check">
                          <div class="slide_Box">
                            <div id="slide" class="nc-container"></div>
                            <div class="container">
                              <form
                                action="http://192.168.0.105/api/Verification_code"
                                method="post"
                              >
                                <input
                                  type="hidden"
                                  id="nc_token"
                                  name="token"
                                />
                                <input
                                  type="hidden"
                                  id="csessionid"
                                  name="session_id"
                                />
                                <input type="hidden" id="scene" name="scene" />
                                <input type="hidden" id="sig" name="sig" />
                                <div class="ln">
                                  <input type="submit" value="提交" />
                                </div>
                              </form>
                            </div>
                          </div>
                        </el-form-item> -->
                      </el-form>
                    </div>

                    <div style="text-align:right;margin-right:25px">
                      <router-link
                        :to="{
                          path: '/login/forgetpass',
                          query: { type: 'audit' }
                        }"
                      >
                        忘记密码?
                      </router-link>
                    </div>
                    <el-button type="primary" @click="dologin" class="login_btn"
                      >登录</el-button
                    >
                    <div style="padding-bottom:40px"></div>
                  </el-tab-pane>
                  <!-- 注册 -->
                  <el-tab-pane label="注册" name="register">
                    <div>
                      <el-form
                        :model="ruleForm"
                        status-icon
                        :rules="rules"
                        ref="ruleForm"
                        label-width="100px"
                        class="demo-ruleForm"
                      >
                        <el-form-item prop="phone">
                          <el-input
                            placeholder="请输入手机号码"
                            v-model.number="ruleForm.phone"
                            clearable
                            class="phonenumipt"
                          >
                            <i
                              slot="prefix"
                              style="font-size:20px;color:#666666;font-weight: bold;"
                              class="el-input__icon el-icon-mobile-phone"
                            ></i>
                          </el-input>
                        </el-form-item>
                        <!-- <el-form-item prop="code">
                          <div
                            style="display:flex;justify-content:space-between;align-items:center;width:380px;margin:0 auto;"
                          >
                            <el-input
                              placeholder="请输入验证码"
                              v-model.number="ruleForm.code"
                              clearable
                              class="phonenumipt authcode"
                            >
                              <i
                                slot="prefix"
                                style="font-size:20px;color:#666666;font-weight: bold;"
                                class="el-input__icon el-icon-chat-line-square"
                              ></i>
                            </el-input>

                            <el-button
                              @click="getCode()"
                              class="login_btn auth"
                              :class="{ 'disabled-style': getCodeBtnDisable }"
                              :disabled="getCodeBtnDisable"
                              >{{ codeBtnWord }}</el-button
                            >
                          </div>
                        </el-form-item> -->
                        <el-form-item prop="pass">
                          <el-input
                            type="password"
                            placeholder="请输入密码"
                            v-model.trim="ruleForm.pass"
                            autocomplete="off"
                            show-password
                            class="phonenumipt"
                          >
                            <i
                              slot="prefix"
                              style="font-size:20px;color:#666666;font-weight: bold;"
                              class="el-input__icon el-icon-lock"
                            ></i>
                          </el-input>
                        </el-form-item>
                        <el-form-item prop="checkPass">
                          <el-input
                            type="password"
                            placeholder="请再次输入密码"
                            v-model.trim="ruleForm.checkPass"
                            autocomplete="off"
                            show-password
                            class="phonenumipt"
                          >
                            <i
                              slot="prefix"
                              style="font-size:20px;color:#666666;font-weight: bold;"
                              class="el-input__icon el-icon-lock"
                            ></i
                          ></el-input>
                        </el-form-item>
                        <el-form-item prop="email">
                          <el-input
                            placeholder="请输入邮箱"
                            v-model.trim="ruleForm.email"
                            clearable
                            class="phonenumipt"
                          >
                            <i
                              slot="prefix"
                              style="font-size:20px;color:#666666;font-weight: bold;"
                              class="el-input__icon el-icon-message"
                            ></i
                          ></el-input>
                        </el-form-item>
                        <el-form-item>
                          <el-button
                            type="primary"
                            class="login_btn"
                            @click="submitForm('ruleForm')"
                            >注册</el-button
                          >
                          <!-- <el-button @click="resetForm('ruleForm')"
                            >重置</el-button
                          > -->
                        </el-form-item>
                      </el-form>
                    </div>
                  </el-tab-pane>
                </el-tabs>
              </div>
            </el-card>
          </div>
        </div>
      </div>
      <div class="footer">
        <footerbox></footerbox>
      </div>
    </div>
    <botloading></botloading>
  </div>
</template>
<script type="text/javascript"></script>
<script>
// import Vue from "vue";
// import { login, getSms, doRegister } from "@/api/local/user";
import { login, getSms, doRegister, Verification } from "@/api/user/user";
import { getUserInfo } from "@/api/userinfo/userinfo";
import botloading from "@/components/botloading.vue";
import logo from "@/components/logo.vue";
import footerbox from "@/components/footerbox.vue";

export default {
  name: "login",
  components: {
    botloading,
    logo,
    footerbox
  },
  data() {
    var checkCode = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("验证码不能为空"));
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error("请输入数字值"));
        } else {
          callback();
        }
      }, 1000);
    };
    var checkPhone = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("手机号不能为空"));
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error("请输入数字值"));
        } else {
          let reg = /^1[3456789]\d{9}$/;
          if (!reg.test(value)) {
            callback(new Error("请填写正确手机号"));
          } else {
            callback();
          }
        }
      }, 1000);
    };
    var checkEmail = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("邮箱不能为空"));
      }
      setTimeout(() => {
        let reg = /^([a-zA-Z]|[0-9])(\w|)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
        // let reg = /^([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/;
        if (!reg.test(value)) {
          callback(new Error("请填写正确的邮箱"));
        } else {
          callback();
        }
      }, 1000);
    };
    var validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请输入密码"));
      } else {
        if (this.ruleForm.checkPass !== "") {
          this.$refs.ruleForm.validateField("checkPass");
        }
        callback();
      }
    };
    var validatePass2 = (rule, value, callback) => {
      if (value === "") {
        callback(new Error("请再次输入密码"));
      } else if (value !== this.ruleForm.pass) {
        callback(new Error("两次输入密码不一致!"));
      } else {
        callback();
      }
    };
    return {
      token: "",
      session_id: "",
      sig: "",
      scene: "register",

      phonenumber: "",
      password: "",
      activeName: "login",
      loginForm: {
        phone: "",
        pass: ""
      },
      ruleForm: {
        phone: "",
        code: "",
        pass: "",
        checkPass: "",
        email: ""
      },
      rules: {
        code: [{ validator: checkCode, trigger: "blur" }],
        phone: [{ validator: checkPhone, trigger: "blur" }],
        pass: [{ validator: validatePass, trigger: "blur" }],
        checkPass: [{ validator: validatePass2, trigger: "blur" }],
        email: [{ validator: checkEmail, trigger: "blur" }]
      },
      codeBtnWord: "获取验证码", // 获取验证码按钮文字
      waitTime: 61 // 获取验证码按钮失效时间
    };
  },
  computed: {
    // 用于校验手机号码格式是否正确
    phoneNumberStyle() {
      let reg = /^1[3456789]\d{9}$/;
      if (!reg.test(this.ruleForm.phone)) {
        return false;
      }
      return true;
    },
    // 控制获取验证码按钮是否可点击
    getCodeBtnDisable: {
      get() {
        if (this.waitTime == 61) {
          if (this.ruleForm.phone) {
            return false;
          }
          return true;
        }
        return true;
      },
      // 注意：因为计算属性本身没有set方法，不支持在方法中进行修改，而下面我要进行这个操作，所以需要手动添加
      set() {}
    }
  },
  created() {
    if (this.$route.query.active) {
      this.activeName = this.$route.query.active;
    }
  },
  mounted() {
    // this.init();
  },
  methods: {
    init() {
      var nc_token = [
        "FFFF0N000000000090C3",
        new Date().getTime(),
        Math.random()
      ].join(":");
      var NC_Opt = {
        renderTo: "#slide",
        appkey: "FFFF0N000000000090C3", //appkey
        scene: "register", //场景值
        token: nc_token,
        customWidth: 300,
        trans: { key1: "code0" },
        elementID: ["usernameID"],
        is_Opt: 0,
        language: "cn",
        isEnabled: true,
        timeout: 3000,
        times: 5,
        apimap: {
          // 'analyze': '//a.com/nocaptcha/analyze.jsonp',
          // 'get_captcha': '//b.com/get_captcha/ver3',
          // 'get_captcha': '//pin3.aliyun.com/get_captcha/ver3'
          // 'get_img': '//c.com/get_img',
          // 'checkcode': '//d.com/captcha/checkcode.jsonp',
          // 'umid_Url': '//e.com/security/umscript/3.2.1/um.js',
          // 'uab_Url': '//aeu.alicdn.com/js/uac/909.js',
          // 'umid_serUrl': 'https://g.com/service/um.json'
        },
        callback: function(data) {
          //组装数据到后台
          document.getElementById("nc_token").value = nc_token;
          document.getElementById("csessionid").value = data.csessionid;
          document.getElementById("sig").value = data.sig;

          // window.console && console.log("nc_token", nc_token);
          // window.console && console.log("csessionid", data.csessionid);
          // window.console && console.log("data.sig", data.sig);
          // 调取接口把数据返回给后端
          Verification({
            token: nc_token, //token
            session_id: data.csessionid, //客户端session
            sig: data.sig, //签名
            scene: "register" //客户端场景(当前pc网页,有两个值H5 pc)
          })
            .then(res => {
              console.log("验证返回", res);
            })
            .catch(err => {
              console.log(err);
            });
        }
      };
      var nc = new noCaptcha(NC_Opt);
      nc.upLang("cn", {
        _startTEXT: "请按住滑块，拖动到最右边",
        _yesTEXT: "验证通过",
        _error300:
          '哎呀，出错了，点击<a href="javascript:__nc.reset()">刷新</a>再来一次',
        _errorNetwork:
          '网络不给力，请<a href="javascript:__nc.reset()">点击刷新</a>'
      });

      var self = this;
      this.nc_token = [this.appKey, new Date().getTime(), Math.random()].join(
        ":"
      );
    },

    getCode() {
      if (this.ruleForm.phone) {
        // 调用获取短信验证码接口// type   register=注册 update-pass = 修改密码
        getSms({
          phone: this.ruleForm.phone,
          type: "register"
        }).then(res => {
          console.log(res);
          if (res.code == 200) {
            this.$message({
              message: "验证码已发送，请稍候查看手机...",
              type: "success",
              center: true
            });
          }
        });
        // 因为下面用到了定时器，需要保存this指向
        let that = this;
        that.waitTime--;
        that.getCodeBtnDisable = true;
        this.codeBtnWord = `${this.waitTime}s 后重新获取`;
        let timer = setInterval(function() {
          if (that.waitTime > 1) {
            that.waitTime--;
            that.codeBtnWord = `${that.waitTime}s 后重新获取`;
          } else {
            clearInterval(timer);
            that.codeBtnWord = "获取验证码";
            that.getCodeBtnDisable = false;
            that.waitTime = 61;
          }
        }, 1000);
      }
    },
    dologin() {
      login({
        phone: this.loginForm.phone,
        password: this.loginForm.pass
      })
        .then(res => {
          console.log("登录成功", res);
          this.$ls.set("token", res.data.token);
          this.$ls.set("usertype", res.data.user_type);
          // console.log(res.data.user_type);
          console.log(this.$ls.get("token"));
          this.$store.commit("SET_TOKEN", res.data.token);
          this.$store.commit("SET_USERTPE", res.data.user_type);
          // console.log(this.$store.state);
          getUserInfo()
            .then(res => {
              if (res.code == 200) {
                console.log("个人信息", res);
                this.$ls.set("userinfo", res.data);
                if (this.$ls.get("usertype") == 1) {
                  this.$router.push("/optimGoods/siftGoods"); //用户
                } else if (this.$ls.get("usertype") == 2) {
                  this.$router.push("/userinfo/homepage"); //推广
                } else if (this.$ls.get("usertype") == 3) {
                  this.$router.push("/userinfo/upgoodshome"); //上单
                } else if (this.$ls.get("usertype") == 4) {
                  this.$router.push("/userinfo/dashboard"); //管理
                } else if (this.$ls.get("usertype") == 5) {
                  this.$router.push("/userinfo/atduhome"); //审核
                }
              } else {
                this.$message.info(res.msg);
              }
            })
            .catch(err => {
              console.log(err);
            });
          if (res.code === 200) {
            this.$message({
              message: res.msg,
              type: "success"
            });
          } else {
            this.$message({
              message: res.msg,
              type: "error"
            });
          }
        })
        .catch(err => {
          console.log(err);
        });
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    submitForm(formName) {
      var that = this;
      this.$refs[formName].validate(valid => {
        if (valid) {
          console.log("注册表单", this.ruleForm);
          doRegister({
            phone: this.ruleForm.phone,
            password: this.ruleForm.checkPass,
            // code: this.ruleForm.code,
            email: this.ruleForm.email
          })
            .then(res => {
              console.log(res);
              this.$message({
                message: "注册成功!",
                type: "success"
              });
              this.resetForm(formName);
              this.activeName = "login";
            })
            .catch(err => {
              console.log(err);
            });
        } else {
          // console.log("error submit!!");
          that.$message.error("请检查填写内容！");
          return false;
        }
      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  }
};
</script>

<style lang="less" scoped>
a {
  text-decoration: none;
  color: #333;
}
.slide_Box::v-deep {
  .nc-container {
    margin: 0 auto;
    width: 360px !important;
    .nc_wrapper {
      width: 360px;
      height: 47px;
      background: #e8e8e8;
      position: relative;
      margin: 0;
      padding: 0;
      .nc_scale {
        width: 360px !important;
        height: 47px;
      }
      .nc_iconfont {
        font-family: "nc_iconfont";
        font-size: 16px;
        font-style: normal;
        width: 57px;
        height: 47px;
        line-height: 47px;
        box-sizing: border-box;
        pointer-events: none;
        left: 0px;
      }
      .nc-lang-cnt {
        height: 47px;
        line-height: 47px;
        font-size: 14px;
        z-index: 0;
        border: none;
        position: static;
        cursor: inherit;
        float: none;
      }
      .nc_bg {
        height: 47px;
      }
    }
  }
}
.login {
  width: 100%;
  .login_main {
    // width: 1200px;
    margin: 0 auto;
    .header {
      width: 100%;
      .header_main {
        overflow: hidden;
        width: 1200px;
        height: 100px;
        margin: 0 auto;
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding-top: 20px;
        padding-bottom: 25px;
        .header_left {
          font-size: 30px;
        }

        .header_action {
          width: 220px;
          height: 68px;
          display: flex;
          justify-content: space-between;
          align-items: center;
          font-size: 10px;
          a:last-child {
            margin-right: 0;
          }
          .action_box {
            display: inline-block;
            width: 50px;
            // height: 58px;
            margin-right: 24px;
            img {
              width: 28px;
            }
          }
        }
      }
    }
    .login_content {
      width: 100%;
      background: url("~@/assets/images/02.png") no-repeat center;
      height: 740px;
      background-position: 50% 0;
      background-size: cover;
      overflow: hidden;
      .content_main {
        width: 1200px;
        margin: 0 auto;
        position: relative;
        .login_box {
          position: absolute;
          top: 40px;
          right: 12px;
          width: 460px;
          height: 465px;
          .login_tabs::v-deep {
            .el-tabs__item.is-top {
              height: 60px;
              font-size: 18px;
              font-weight: bold;
              width: 209px;
            }
            .phonenumipt {
              width: 360px;
              margin: 10px;
              .el-input__inner {
                // font-weight: bold;
                height: 47px;
                box-sizing: border-box;
                background-color: #f7f8fa;
                border: 2px solid transparent;
              }
              .el-input__inner:hover {
                border: 2px solid #6183ff;
              }
            }
            .phonenumipt .authcode {
              width: 220px;
              margin: 10px;
              .el-input__inner {
                // font-weight: bold;
                height: 47px;
                box-sizing: border-box;
                background-color: #f7f8fa;
                border: 2px solid transparent;
              }
              .el-input__inner:hover {
                border: 2px solid #6183ff;
              }
            }
            .login_btn {
              margin-top: 20px;
              border-radius: 13px;
              font-size: 16px;
              padding: 17px 163px !important;
              background: linear-gradient(
                90deg,
                rgba(87, 148, 255, 1),
                rgba(107, 102, 255, 1)
              );
              transition: all 300ms ease;
            }
            .login_btn.auth {
              color: white;
              margin-top: 0px;
              border-radius: 13px;
              font-size: 16px;
              padding: 16px 19px !important;
              background: linear-gradient(
                90deg,
                rgba(87, 148, 255, 1),
                rgba(107, 102, 255, 1)
              );
              transition: all 300ms ease;
            }
            .login_btn:hover {
              transform: translateY(-5px);
              background: linear-gradient(
                90deg,
                rgba(107, 102, 255, 1),
                rgba(87, 148, 255, 1)
              );
            }
            .el-form-item__error {
              color: #f56c6c;
              font-size: 12px;
              line-height: 1;
              padding-top: 4px;
              position: absolute;
              top: 100%;
              left: 35px;
            }
            .el-form-item__content {
              line-height: 40px;
              position: relative;
              font-size: 14px;
              margin-left: 0 !important ;
            }
            .el-button.disabled-style {
              background-color: #eeeeee;
              color: white;
            }
          }
        }
      }
    }
    .footer {
      width: 100%;
      .footer_link {
        width: 1200px;
        margin: 0 auto;
        display: flex;
        justify-content: space-around;
        align-items: center;
        padding: 10px;
        // a {
        // }
        a:hover {
          color: blue;
        }
      }
    }
  }
}
</style>
